import React, { useState, useEffect, useRef } from 'react'
import styled from 'styled-components'
import Logout from '../components/Logout';
import ChatInput from '../components/ChatInput';
import axios from "axios";
import { sendMessageRoute } from '../utils/APIRoutes';
import { getAllMessagesRoute } from '../utils/APIRoutes';
import { v4 as uuidv4 } from "uuid";

export default function ChatContainer({ currentChat, currentUser, socket }) {

    const [messages, setMessages] = useState([]);
    const [arrivalMessage, setArrivalMessage] = useState(null);
    const scrollRef = useRef(null);

    useEffect(() => {
        if (currentChat) {
            const asyncFunc = async () => {
                const res = await axios.post(getAllMessagesRoute, {
                    from: currentUser._id,
                    to: currentChat._id
                });
                setMessages(res.data);
            }
            asyncFunc();
        }
    }, [currentChat]);


    const handleSendMsg = async (msg) => {
        if (socket !== undefined && socket.current !== undefined) {
            // 保存到数据库
            await axios.post(sendMessageRoute, {
                from: currentUser._id,
                to: currentChat._id,
                message: msg
            });

            // socket 实时通信
            socket.current.emit('send-msg', {
                to: currentChat._id,
                from: currentUser._id,
                msg: msg
            });

            const msgs = [...messages];

            msgs.push({ fromSelf: true, message: msg });
            setMessages(msgs);
        }
    }

    useEffect(() => {
        if (socket.current) {
            socket.current.on('receive-msg', (data) => {
                setArrivalMessage({ fromSelf: false, message: data });
            });

        }
    }, []);

    useEffect(() => {
        arrivalMessage && setMessages((prev) => [...prev, arrivalMessage]);
    }, [arrivalMessage]);

    useEffect(() => {
        scrollRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    return (
        <>
            <Container>
                <div className="chat-header">
                    <div className="user-details">
                        <div className="avatar">
                            <img src={`data:image/svg+xml;base64,${currentChat.avatarImage}`} alt="avatar" />
                        </div>
                        <div className="username">
                            <h3>{currentChat.username}</h3>
                        </div>
                    </div>
                    <Logout></Logout>
                </div>
                <div className="chat-messages">
                    {
                        messages.map((message, index) => {
                            return (
                                <div ref={scrollRef} key={uuidv4()}>
                                    <div className={`message ${message.fromSelf ? "sended" : "received"}`}>
                                        <div className="content">
                                            <p>{message.message}</p>
                                        </div>
                                    </div>
                                </div>
                            )
                        })
                    }
                </div>
                <ChatInput handleSendMsg={handleSendMsg}></ChatInput>
            </Container>
        </>
    )
}

const Container = styled.div`
    padding-top: 1rem;
    display: grid;
    grid-template-rows: 10% 78% 12%;
    gap: 0.1rem;
    overflow: hidden;
    @media screen and (min-width: 720px) and (max-width: 1080px){
        grid-auto-rows: 15% 70% 15%;
    } 

    .chat-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 2rem;

        .user-details {
            display: flex;
            align-items: center;
            gap: 1rem;

            .avatar {
                img {
                    height: 3rem;
                }
            }

            .username {
                h3 {
                    color: white;
                }
            }
        }
    }

    .chat-messages {
        padding: 1rem 2rem;
        display: flex;
        flex-direction: column;
        gap: 1rem;
        overflow: auto;

        &::-webkit-scrollbar {
            background-color: #080420;
            width: 5px;
            &-thumb {
                background-color: #9186f3;
            }
        }

        .message {
            display: flex;
            align-items: center;

            .content {
                max-width: 40%;
                overflow-wrap: break-word;
                padding: 1rem;
                color: #d1d1d1;
                font-size: 1.1rem;
                border-radius: 1rem;
            }
        }

        .sended {
            justify-content: flex-end;

            .content {
                background-color: #9900ff20;
            }
        }
    }
`;
